<template>
  <div class="component-container">
    <div class="component-container__main">
      <el-card class="box-card">
        <template #header>
          <span>商品规格</span>
          <el-button type="success" size="small" class="float-right" @click="handleSpecAdd">
            <i-ep-plus /> 添加规格项
          </el-button>
        </template>
        <el-form :model="specForm" label-width="auto" ref="specFormRef">
          <el-table :data="specForm.specList">
            <el-table-column align="center" width="50">
              <template #default>
                <svg-icon class="drag-handler" icon-class="drag" />
              </template>
            </el-table-column>
            <el-table-column label="规格名" width="200">
              <template #default="scope">
                <el-form-item>
                  <el-input v-model="scope.row.name" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column>
              <template #header>
                规格值
                <el-link type="danger" style="font-size: 12px" :underline="false"
                  >（默认第一条规格包含图片）</el-link
                >
              </template>
              <template #default="scope">
                <div
                  v-for="item in scope.row.values"
                  :key="item.id"
                  style="display: inline-block; margin-right: 15px"
                >
                  <el-tag type="primary">{{ item.value }}</el-tag>
                  <SingleUpload v-model="item.imgUrl" v-if="scope.$index == 0" />
                </div>
                <el-input
                  v-if="tagInputs.length > 0 && tagInputs[scope.$index].visible"
                  v-model="tagInputs[scope.$index].value"
                  style="width: 80px; vertical-align: top"
                  size="small"
                  @keyup.enter="handleSpecValueInput(scope.$index)"
                  @blur="handleSpecValueInput(scope.$index)"
                />
                <el-button
                  v-else
                  style="vertical-align: top"
                  size="small"
                  @click="addSpecValue(scope.$index)"
                >
                  <i-ep-plus /> 添加规格值
                </el-button>
              </template>
            </el-table-column>
            <el-table-column width="60" label="操作">
              <template #default="scope">
                <el-button
                  type="danger"
                  size="small"
                  plain
                  @click.stop="handleSpecDelete(scope.$index)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-card>
      <el-card class="box-card">
        <template #header>
          <span>商品库存</span>
        </template>
        <el-form :model="skuForm" label-width="auto" ref="skuFormRef">
          <el-table
            :data="skuForm.skuList"
            :span-method="(objectSpanMethod as any)"
            highlight-current-row
            size="small"
            border
          >
            <el-table-column
              v-for="(title, index) in specTitle"
              :key="index"
              align="center"
              :prop="'specValue' + (index + 1)"
              :label="title"
            />
            <el-table-column label="商品编码">
              <template #default="scope">
                <el-form-item>
                  <el-input v-model="scope.row.skuSn" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="价格">
              <template #default="scope">
                <el-form-item>
                  <el-input v-model="scope.row.price" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="库存">
              <template #default="scope">
                <el-form-item>
                  <el-input v-model="scope.row.stockNum" />
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-form>
      </el-card>
    </div>
    <div class="component-container__footer">
      <el-button @click="handlePrev">上一步，设置商品属性</el-button>
      <el-button type="primary" @click="submitForm">提交</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { getAttributeList } from '@/api/pms/attribute'
import { addSpu, updateSpu } from '@/api/pms/goods'
const props = defineProps({
  modelValue: {
    type: Object,
    default: () => {
      return {}
    }
  }
})
const emit = defineEmits(['prev', 'next', 'update:modelValue'])
const goodsInfo = computed({
  get: () => props.modelValue,
  set: (val) => {
    emit('update:modelValue', val)
  }
})
const specFormRef = ref(ElForm)
const skuFormRef = ref(ElForm)
const router = useRouter()

const state = reactive({
  specForm: {
    specList: [] as any[]
  },
  skuForm: {
    skuList: [] as any[]
  },
  specTitle: [] as any[],
  rules: {
    spec: {
      name: [{ required: true, message: '请输入规格名称', trigger: 'blur' }],
      value: [{ required: true, message: '请输入规格值', trigger: 'blur' }]
    },
    sku: {
      skuSn: [{ required: true, message: '请输入商品编号', trigger: 'blur' }],
      price: [{ required: true, message: '请输入商品价格', trigger: 'blur' }],
      stockNum: [{ required: true, message: '请输入商品库存', trigger: 'blur' }]
    }
  },
  tagInputs: [{ value: undefined, visible: false }] // 规格值标签临时值和显隐控制
})
const { specForm, skuForm, specTitle, rules, tagInputs } = toRefs(state)

// 侦听分类里面的商品的变化
// 获取当前商品的ID 存在就返回false 不继续后面的操作 不存在继续往下面走
watch(
  () => goodsInfo.value.categoryId,
  (newVal) => {
    const goodsId = goodsInfo.value.id
    if (goodsId) {
      return false
    }
    if (newVal) {
      getAttributeList({ categoryId: newVal, type: 1 }).then((res) => {
        const specList = res.data
        if (specList && specList.length > 0) {
          specList.forEach((item: any) => {
            state.specForm.specList.push({
              name: item.name,
              values: []
            })
          })
        }
      })
    }
  },
  {
    immediate: true,
    deep: true
  }
)
const loadData = () => {
  console.log(goodsInfo.value.specList)
  console.log(goodsInfo.value.skuList)

  goodsInfo.value.specList.forEach((specItem: any) => {
    const specIndex = state.specForm.specList.findIndex((item: any) => item.name == specItem.name)
    if (specIndex > -1) {
      state.specForm.specList[specIndex].values.push({
        id: specItem.id,
        value: specItem.value,
        picUrl: specItem.picUrl
      })
    } else {
      state.specForm.specList.push({
        name: specItem.name,
        values: [
          {
            id: specItem.id,
            value: specItem.value,
            picUrl: specItem.picUrl
          }
        ]
      })
    }
  })
  // 每个规格项追加一个添加添加规格值按钮
  for (let i = 0; i < state.specForm.specList.length; i++) {
    state.tagInputs.push({ value: undefined, visible: false })
  }

  //sku规格ID 拼接字符串处理
  goodsInfo.value.skuList.forEach((item: any) => {
    item.specIdArr = item.specIds.split('_')
  })

  getTitle()
  generateSkuList()
  handleSpecReorder()
}

const getTitle = () => {
  const specList = JSON.parse(JSON.stringify(state.specForm.specList))
  console.log(specList)
  state.specTitle = specList.map((item: any) => item.name)
}

const handleSpecReorder = () => {
  state.specForm.specList.forEach((item, index) => {
    item.index = index
  })
}

//添加规格项
const handleSpecAdd = () => {
  if (state.specForm.specList.length >= 4) {
    ElMessage.warning('最多支持4组规格')
    return
  }
  state.specForm.specList.push({ values: [] })
  state.tagInputs.push({ value: undefined, visible: false })
  handleSpecReorder()
}

//删除规格项
const handleSpecDelete = (index: number) => {
  state.specForm.specList.splice(index, 1)
  state.tagInputs.splice(index, 1)
  generateSkuList()
  handleSpecReorder()
  getTitle()
}

// 根据商品规格笛卡尔积生成SKU列表
const generateSkuList = () => {
  console.log(state.specForm.specList)

  // 规格为空
  if (state.specForm.specList.length == 0) {
    state.skuForm.skuList = []
    return
  }

  const specList = JSON.parse(
    // 深拷贝
    JSON.stringify(
      state.specForm.specList.filter((item: any) => item.values && item.values.length > 0)
    )
  )
  console.log(specList)

  const skuList = specList.reduce(
    (prev: any, next: any) => {
      let result = [] as any[]
      prev.forEach((item: any) => {
        // {specValues: '', specIds: ''}
        next.values.forEach((value: any) => {
          // {id: 841, value: '16g', picUrl: null}
          let temp = Object.assign({}, item)
          temp.specValues += value.value + '_'
          temp.specIds += value.id + '|'
          result.push(temp)
        })
      })
      return result
    },
    [{ specValues: '', specIds: '' }]
  )

  skuList.forEach((item: any) => {
    // console.log(item)
    item.specIds = item.specIds.substring(0, item.specIds.length - 1)
    item.name = item.specValues.substring(0, item.specValues.length - 1).replaceAll('_', '')

    const specIdArr = item.specIds.split('|')
    const sku = goodsInfo.value.skuList.filter(
      (item: any) =>
        item.specIdArr.length === specIdArr.length &&
        // 判断第一个数组中的每个元素是否都存在于第二个数组中。如果不存在，直接返回false。
        // every() 方法测试一个数组内的所有元素是否都能通过指定函数的测试。它返回一个布尔值。
        // some() 方法测试数组中是否至少有一个元素通过了由提供的函数实现的测试。
        // 如果在数组中找到一个元素使得提供的函数返回 true，则返回 true；否则返回 false。它不会修改数组。
        item.specIdArr.every((a: any) => specIdArr.some((b: any) => a === b)) &&
        // 判断第二个数组中的每个元素是否都存在于第一个数组中。如果不存在，直接返回false。
        specIdArr.every((x: any) => item.specIdArr.some((y: any) => x === y))
    )
    if (sku && sku.length > 0) {
      const skus = sku[0]
      item.id = skus.id
      item.skuSn = skus.skuSn
      item.price = skus.price / 100
      item.stockNum = skus.stockNum
    }
    // 方法用于从字符串中提取子字符串，这里从索引0开始，
    const specValueArr = item.specValues.substring(0, item.specValues.length - 1).split('_')
    specValueArr.forEach((value: any, index: any) => {
      const key = 'specValue' + (index + 1)
      item[key] = value
      if (index == 0 && state.specForm.specList.length > 0) {
        const valueIndex = state.specForm.specList[0].values.findIndex(
          (item: any) => item.value == value
        )
        if (valueIndex > -1) {
          item.picUrl = state.specForm.specList[0].values[valueIndex].picUrl
        }
      }
    })
  })
  state.skuForm.skuList = JSON.parse(JSON.stringify(skuList))
}

const addSpecValue = (index: any) => {
  state.tagInputs[index].visible = true
}

const handleSpecValueInput = (index: any) => {
  const currSpecValue = state.tagInputs[index].value
  const specValues = state.specForm.specList[index].values
  console.log(state.specForm.specList[index].values)

  console.log(specValues)

  if (
    specValues &&
    specValues.length > 0 &&
    specValues.map((item: any) => item.value).includes(currSpecValue)
  ) {
    ElMessage.warning('规格值重复，请重新输入')
    return false
  }
  if (currSpecValue) {
    if (specValues && specValues.length > 0) {
      console.log(specValues)

      let SpecValueIndex = specValues
        .filter((item: any) => item.id.includes('tid_'))
        .map((item: any) => item.id.split('_')[2])
        .reduce((prev: any, next: any) => {
          return prev > next ? prev : next
        }, 0)
      state.specForm.specList[index].values[specValues.length] = {
        value: currSpecValue,
        id: 'tid_' + (index + 1) + '_' + ++SpecValueIndex
      }
    } else {
      state.specForm.specList[index].values = [
        { value: currSpecValue, id: 'tid_' + (index + 1) + '_1' }
      ]
    }
  }
  state.tagInputs[index].value = undefined
  state.tagInputs[index].visible = false
  generateSkuList()
}

const handleSpecValueDelete = (index: any, specValueIndex: any) => {
  state.specForm.specList[index].values.splice(specValueIndex, 1)
}

const submitForm = () => {
  if (!state.skuForm.skuList || state.skuForm.skuList.length === 0) {
    ElMessage.warning('未添加商品库存')
    return false
  }
  specFormRef.value.validate((specvalid: any) => {
    if (specvalid) {
      skuFormRef.value.validate((slivalid: any) => {
        if (slivalid) {
          let submitsData = Object.assign({}, goodsInfo.value)
          delete submitsData.specList
          delete submitsData.skuList

          let specList = [] as any[]
          state.specForm.specList.forEach((item: any) => {
            item.values.forEach((value: any) => {
              value.name = item.name
            })
            specList = specList.concat(item.values)
          })
          submitsData.specList = specList
          submitsData.price *= 100
          submitsData.originPrice *= 100

          let skuList = JSON.parse(JSON.stringify(state.skuForm.skuList))
          skuList.map((item: any) => {
            item.price *= 100
            return item
          })
          submitsData.skuList = skuList
          const goodsId = goodsInfo.value.id
          if (goodsId) {
            // 编辑商品提交
            updateSpu(goodsId, submitsData).then(() => {
              router.push({ path: '/pms/goods' })
              ElMessage.warning('修改成功')
            })
          } else {
            // 新增商品提交
            addSpu(submitsData).then(() => {
              router.push({ path: '/pms/goods' })
              ElMessage.warning('添加成功')
            })
          }
        }
      })
    }
  })
}

const objectSpanMethod = ({ rowIndex, columnIndex }: any) => {
  let mergeRows = [1, 1, 1]
  const specLen = state.specForm.specList.filter(
    (item) => item.values && item.values.length > 0
  ).length
  if (specLen == 2) {
    const lenTwo = state.specForm.specList[1].values ? state.specForm.specList[1].values.length : 1
    mergeRows = [lenTwo, 1, 1]
  } else if (specLen == 3) {
    const lenTwo = state.specForm.specList[1].values ? state.specForm.specList[1].values.length : 1
    const lenThree = state.specForm.specList[2].values
      ? state.specForm.specList[2].values.length
      : 1
    mergeRows = [lenTwo, lenThree, 1]
  }
  if (columnIndex == 0) {
    if (rowIndex % mergeRows[0] === 0) {
      return [mergeRows[0], 1] // 合并单元格
    } else {
      return [0, 0] // 隐藏单元格
    }
  }
  if (columnIndex == 1) {
    if (rowIndex % mergeRows[1] === 0) {
      return [mergeRows[1], 1] // 合并单元格
    } else {
      return [0, 0] // 隐藏单元格
    }
  }
}

// 上一步
const handlePrev = () => {
  emit('prev')
}
onMounted(() => {
  loadData()
})
</script>

<style scoped lang="scss">
</style>